//
//  SFNetworkTools.swift
//  swift访问网络
//
//  Created by 孙凡 on 16/4/10.
//  Copyright © 2016年 Edward. All rights reserved.
//

import UIKit
import AFNetworking


enum SFRequestMethod:String {
    case GET = "GET"
    case POST = "POST"
}


class SFNetworkTools: AFHTTPSessionManager {

    static let sharedTools :SFNetworkTools = { () -> SFNetworkTools in

        let tools = SFNetworkTools()

        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        tools.responseSerializer.acceptableContentTypes?.insert("application/json;charset=UTF-8")

//        tools.responseSerializer = AFHTTPResponseSerializer()

        return tools

    }()

    func request (method: SFRequestMethod, URLString: String, parameters: AnyObject?, callBack:((responseObjct: AnyObject?, error: NSError?) -> ())){


        /**
         let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) in

         // 判断返回数据是否是一个字典
         guard let responseDict = responseObject as? [String: AnyObject] else {
         // 如果发现不是字典
         callback(responseObject: nil, error: NSError(domain: "com.itheima.hahaha", code: 10001, userInfo: ["message": "返回数据不是字典"]))
         return
         }
         // 回调数据
         callback(responseObject: responseDict, error: nil)
         }
        */

        let success = { (dataTask: NSURLSessionDataTask, responseObject: AnyObject?) in

//            guard ((responseObject as? [String: AnyObject?]) != nil) else {
//
//                callBack(responseObjct: nil, error: NSError(domain: "sssssss", code: 10000, userInfo: ["message": "返回数据不是字典"]))
//
//                return
//            }

            callBack(responseObjct: responseObject, error: nil)
        }


        let failure = { (dataTask: NSURLSessionDataTask?, err: NSError) in

            callBack(responseObjct: nil, error: err)
        }




        if method == SFRequestMethod.GET {

            self.GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else {

            self.POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)

        }

    }



}
